﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProcessMonitor
{
    public partial class FrmAdd : Form
    {
        private ProcessInfo proModel = null;
        public FrmAdd(ProcessInfo _proInfo)
        {
            proModel = _proInfo;
            InitializeComponent();
        }

        private void FrmAdd_Load(object sender, EventArgs e)
        {
            if (proModel == null)
            {
                this.Text = "添加新进程";
            }
            else
            {
                this.Text = "编辑进程信息";

                tbProName.Text = proModel.Name;
                tbProNameCn.Text = proModel.Desc;
                tbProPath.Text = proModel.Path;
                if (proModel.AutoReboot == "") rbreboot_0.Checked = true;
                else if (proModel.AutoReboot.StartsWith("day")) rbreboot_day.Checked = true;
                else if (proModel.AutoReboot.StartsWith("week"))
                {
                    rbreboot_week.Checked = true;
                    rb_cb_weeknum.Text = proModel.AutoReboot.Split('_')[1];
                }

                else if (proModel.AutoReboot.StartsWith("mouth"))
                {
                    rbreboot_mouth.Checked = true;
                    rb_tb_daynum.Text = proModel.AutoReboot.Split('_')[1];
                }
                tbreboottime.Text = proModel.RebootTimeSet;

                tbMemSize.Text = proModel.LimitMemory.ToString();
            }
        }

        /// <summary>
        /// 新增 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(tbProName.Text)
                || string.IsNullOrWhiteSpace(tbProPath.Text)
                || string.IsNullOrWhiteSpace(tbProNameCn.Text))
            {
                MessageBox.Show("必填项不能为空，请输入。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var limitMemory = 0L;

            if (!long.TryParse(tbMemSize.Text.Trim(), out limitMemory))
            {
                MessageBox.Show("内存限制必须为整数,如果不需要设置，请默认为0");
                return;
            }

            var proname = tbProName.Text.Trim().Split(' ')[0];

            if (!File.Exists(tbProPath.Text + Path.DirectorySeparatorChar + proname))
            {
                MessageBox.Show("当前文件不存在，请修改后重试。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            #region 判断是否重复

            var existpros = ProcessData.processlist.Where(p => p.Path == tbProPath.Text.Trim() && p.Name == proname).ToList();

            if (existpros != null && existpros.Count() > 0)
            {
                //编辑的时候
                if (proModel != null)
                {
                    var temp = existpros.FirstOrDefault(p => p.IndexNum != proModel.IndexNum);
                    if (temp != null)
                    {
                        if (MessageBox.Show($"编辑存在相同的配置，对应序号[{temp.IndexNum}]，是否确认保存？", "重复提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        {
                            return;
                        }
                    }
                }
                else
                {
                    if (MessageBox.Show($"新增存在相同的配置，对应序号[{existpros[0].IndexNum}]，是否确认保存？", "重复提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        return;
                    }
                }
            }

            #endregion

            #region 重启配置验证
            var rebootset = "";
            if (rbreboot_0.Checked) rebootset = "";
            else if (rbreboot_day.Checked) rebootset = "day";
            else if (rbreboot_mouth.Checked)
            {
                if (rb_tb_daynum.Text.Trim() == "")
                {
                    MessageBox.Show("按周自动重启 必须选择日期");
                    return;
                }
                rebootset = "mouth_" + rb_tb_daynum.Text.Trim();
            }
            else if (rbreboot_week.Checked)
            {
                if (rb_cb_weeknum.Text.Trim() == "")
                {
                    MessageBox.Show("按月自动重启 必须选择号数");
                    return;
                }
                rebootset = "week_" + rb_cb_weeknum.Text.Trim();
            }
            #endregion

            #region 杀原进程
            if (proModel != null)
            {
                var findpro = Process.GetProcessesByName(proModel.Name.Split(' ')[0].Replace(".exe", "")).FirstOrDefault(p => p.MainModule.FileName == proModel.Path + Path.DirectorySeparatorChar + proModel.Name.Split(' ')[0]);
                if (findpro != null && findpro.Id > 0)
                {
                    findpro.Kill();
                    ProcessData.processlist[proModel.IndexNum].PID = "0";
                    ProcessData.processlist[proModel.IndexNum].IsDie = true;
                }
            }
            #endregion


            ProLogic.Instance.SyncAddEditToXml(tbProName.Text, tbProPath.Text, tbProNameCn.Text, proModel?.IndexNum, rebootset, tbreboottime.Text.Trim(), limitMemory);

            this.Close();
        }

        private void btnNo_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dia = new FolderBrowserDialog() { SelectedPath = tbProPath.Text };
            if (dia.ShowDialog() == DialogResult.OK)
            {
                tbProPath.Text = dia.SelectedPath;
            }
        }
    }
}
